public class LC5M {
    public String longestPalindrome(String s) {
        int n=s.length();
        char[] ch=s.toCharArray();
        int maxLength=0;
        String maxString="";
        for (int i = 0; i < n; i++) {
            int left=i-1,right=i+1;
            int count=1;
            boolean flag=true;
            while (left>=0 && right<=n-1){
                if (ch[left]==ch[right]){
                    if (ch[left]!=ch[i])
                        flag=false;
                    left--;
                    right++;
                    count+=2;
                }
                else if (ch[left]==ch[i] && flag){
                    left--;
                    count+=1;
                }
                else {
                    break;
                }
            }
            while (left>=0 && flag){
                if (ch[left]==ch[i]){
                    left--;
                    count++;
                }
                else
                    break;
            }
            if (count>maxLength){
                maxLength=count;
                maxString=s.substring(left+1,right);
            }
        }
        return maxString;
    }
}
